package com.yang.filter;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yang.pojo.User;

public class LoginFilter implements Filter {

	private String str="";
	@Override
	public void destroy() {
	}
	private Logger log=Logger.getLogger(this.getClass().getName());

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		if(str==null||"".equals(str)){
			chain.doFilter(req, resp);
		}else{
			HttpServletRequest request=(HttpServletRequest)req;
			HttpServletResponse response=(HttpServletResponse)resp;
			StringBuffer sb=request.getRequestURL();
			InputStream is=this.getClass().getClassLoader().getResourceAsStream("filter.properties");
			Properties pp=new Properties();
			pp.load(is);
			String s=sb.substring(sb.lastIndexOf("/")+1);
			String s1=sb.substring(sb.lastIndexOf(".")+1);
			log.warning(s);
			log.warning(s1);
			HttpSession session =request.getSession();
			User u=(User)session.getAttribute("user");
			if(u!=null){
				if(u.getName()!=null){
					chain.doFilter(req, resp);
				}else{
					response.sendRedirect("index.jsp");
				}
			}else{
				if(s!=null&&s1!=null&&(pp.containsKey(s)||pp.containsKey(s1))){
					chain.doFilter(req, resp);
				}else{
					response.sendRedirect("index.jsp");
				}
			}
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		str=config.getInitParameter("isFilter");
		log.warning("配置是否登录过滤器 isFilter的值为："+str);
	}

}
